//
//  Net.swift
//  二次源
//
//  Created by 李建文 on 2016/11/22.
//  Copyright © 2016年 二次源. All rights reserved.
//

import UIKit
import SwiftHTTP

//http请求类
class Net {
    
    //url地址
    public var url:String = "http://192.168.137.1:8080/ecy1.0"
    
    public var data:JSON = []
    
    //参数字典
    public var params:Dictionary<String,String> = [:]
    
    //#MARK:GET请求
    
    //不带参数的
    func sendGetWithoutParam(){
        do {
            let opt = try HTTP.GET(self.url)
            opt.start { response in
                //利用自带的json库转换成Data
                //如果设置options为JSONSerialization.WritingOptions.prettyPrinted，则打印格式更好阅读
                let data = try? JSONSerialization.data(withJSONObject: response, options: [])
                //Data转换成String打印输出
                let str = String(data:data!, encoding: String.Encoding.utf8)
                //输出json字符串
                print("Json Str:"); print(str)
                
                }
        } catch let error {
            print("请求失败: \(error)")
        }
    }
    
    //带参数的
    func sendGetWithParam(){
        do {
            
            let opt = try HTTP.GET(self.url,
                                   parameters:self.params)
            opt.start { response in
                //进行具体的响应操作...
            }
        } catch let error {
            print("请求失败: \(error)")
        }
    }
    
    //#MARK:POST请求
    
    func sendPostWithParam(){
       
        print(self.url)
        //创建URL对象
        let urls = URL(string: self.url)
        //创建请求对象
        let request = URLRequest(url: urls!)
        
        let dataTask = URLSession.shared.dataTask(with: request,
                                                  completionHandler: {(data, response, error) -> Void in
                                                    if error != nil{
                                                        print(error)
                                                    }else{
                                                        let json = JSON(data: data!)
                                                        self.data = json
                                                    }
        }) as URLSessionTask
        
        //使用resume方法启动任务
        dataTask.resume()
    }
   
    
    //#MARK:添加参数
    func addParames(key:String, value:String){
        self.params[key]=value
    }
    
    
    func getData() -> JSON{
        return self.data
    }
    
    func addUrl(url:String){
        self.url = self.url + url
    }
    
}
